package com.eims.sls_app.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.bx.pay.WPayApplication;
import com.eims.sls_app.dataaccess.LotteryContent;
import com.eims.sls_app.dataaccess.Schemes;
import com.eims.sls_app.fragment.CircleFragment;
import com.eims.sls_app.fragment.CircleFragment_viewpage_god;
import com.eims.sls_app.fragment.CircleFragment_viewpage_whole;
import com.eims.sls_app.fragment.FollowFragment;
import com.eims.sls_app.fragment.HallFragment;
import com.eims.sls_app.fragment.LiveScoresFragment;
import com.eims.sls_app.fragment.MyCenterFragment;
import com.eims.sls_app.fragment.WinLotteryFragment;
import com.eims.sls_app.fragment.myLiveScoresFragment;
import com.eims.sls_app.ui.win_dialog.widget.Effectstype;
import com.eims.sls_app.ui.win_dialog.widget.NiftyDialogBuilder;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.AppTools;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.PushUtil;
import com.eims.sls_app.utils.RequestUtil;
import com.eims.sls_app.view.ConfirmDialog;
import com.eims.sls_app.view.VibratorView;

import com.listener.OnHallDanguanPaySureListener;
import com.testin.agent.TestinAgent;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import bls.juejin.cn.R;

public class MainActivity extends MyFragmentActivity implements OnClickListener, OnHallDanguanPaySureListener {

	public static final String TAG = "MainActivity";
	private Context context = MainActivity.this;
	boolean falg = true; // 标签，对象是否为同一天发起。
	public static Fragment scrollView;

	private ImageView iv_tab_hall, iv_tab_follow, iv_tab_win, iv_tab_info, iv_tab_center;// 主页面图标
	private LinearLayout layout_tab_hall, layout_tab_follow, layout_tab_info, layout_tab_win, layout_tab_center;// 图标布局

	private TextView tv_tab_hall, tv_tab_follow, tv_tab_win, tv_tab_info, tv_tab_center;
	public static LocalActivityManager manager;

	private String opt, auth, info, time, imei, crc; // 格式化后的参数

	private String pass;
	private String name;

	private Intent intent;
	private long firstTime = 0;

	public static FragmentTransaction transaction;

	public static LinearLayout ll_main;
	public static LinearLayout ll_main_1;

	// public static MyHandler genxinHandler;

	private UpdateManager mUpdateManager;

	private String downLoadUrl;
	private ConfirmDialog dialog;// 提示框

	private Effectstype effect;
	public Vibrator vibrator; // 震动器
	private SharedPreferences settings;// 保存购彩大厅彩种id位置
	private List<List<Schemes>> listAllSchemes = new ArrayList<List<Schemes>>();
	private List<String> list = new ArrayList<String>();
	private List<Schemes> listDetail;
	public static boolean isWin = false;
	private List<RequestUtil> requestUtils;
	private int indexId;
	public HallFragment mHallFragment = new HallFragment();
	public Fragment mFragment;
	private LiveScoresFragment mLiveScoresFragment = new LiveScoresFragment();
	public FollowFragment mFollowFragment = new FollowFragment();
	public WinLotteryFragment mWinLotteryFragment = new WinLotteryFragment();
	public MyCenterFragment mMyCenterFragment = new MyCenterFragment();

	private RelativeLayout rl_top_choice;
	private TextView tvWhole, tvGod;
	private int ChoiceIndex = 1;

	private ImageView ivSearch;

	private ImageView iv_start;
	private RelativeLayout rlInfoShow;
	private TextView tvInfonum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate");
		// 设置无标题
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		for (int i = 0; i < App.activityS.size(); i++) {
			App.activityS.get(i).finish();
			Log.e("xxxxx", "main清除所有");
		}
		App.activityS.clear();
		setContentView(R.layout.activity_main);




		Window window = getWindow();

		window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		ViewGroup decorViewGroup = (ViewGroup) window.getDecorView();
		View statusBarView = new View(window.getContext());
		int statusBarHeight = getStatusBarHeight(window.getContext());
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, statusBarHeight);
		params.gravity = Gravity.TOP;
		statusBarView.setLayoutParams(params);
		statusBarView.setBackgroundColor(Color.parseColor("#E4373B"));
		decorViewGroup.addView(statusBarView);



		WPayApplication.initEnv(MainActivity.this);

		App.activityS.add(this);

		getVersion(); // 得到版本号
		vibrator = VibratorView.getVibrator(getApplicationContext());
		startPush();
		TestinAgent.init(context, "80cfb8a537e67d8802816c451b5082f5", "wandoujia");
		/*
		 * TestinAgent.init(context, "fd3b855a025aadacbc79dab1e0e5aff5", "wandoujia");
		 */

		init();
	}
	private  int getStatusBarHeight(Context context) {
		int statusBarHeight = 0;
		Resources res = context.getResources();
		int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			statusBarHeight = res.getDimensionPixelSize(resourceId);
		}
		return statusBarHeight;
	}

	@Override
	public Resources getResources() {
		// TODO Auto-generated method stub
		Resources res = super.getResources();
		Configuration config = new Configuration();
		config.setToDefaults();
		res.updateConfiguration(config, res.getDisplayMetrics());
		return res;
	}

	@Override
	protected void onResumeFragments() {
		if (App.list_numbers != null && App.totalCount != 0) {
			App.list_numbers.clear();
			App.totalCount = 0;
		}
		if (App.list_numbers != null) {
			App.list_numbers.clear();
		}
		if (App.totalCount != 0) {
			App.totalCount = 0;
		}
		super.onResumeFragments();
	}

	/**
	 * 初始化整个程序需要的数据,并设置fragment
	 */
	private void init() {
		settings = this.getSharedPreferences("hall_lotterys", 0);
		boolean isSaved = false;// 有没有保存的标识
		if (settings.contains("isSavelottery")) {
			isSaved = settings.getBoolean("isSavelottery", false);
		}
		if (settings.contains("lotterysId")) {
			App.lotterysId = settings.getString("lotterysId", null);
		}
		System.out.println("==== 有没有保存的标识===" + isSaved + "保存的彩种id的顺序===" + App.lotterysId);

		if (App.allLotteryLogo == null) {
			AppTools.setLogo();
		}
		findView(); // 得到控件
		setListener(); // 设置监听
		setFragment();
		if (null == requestUtils)
			requestUtils = new ArrayList<RequestUtil>();
		updateversions();// 判断执行版本更新
		getScaleParams();// 获取佣金比例和认购比例
		// getSiteNameAndPhone();//获取站点名称和客服电话

		// downloadImg();

	}

	public void startPush() {
		// Push: 以apikey的方式登录，一般放在主Activity的onCreate中。
		// 这里把apikey存放于manifest文件中，只是一种存放方式，
		// 您可以用自定义常量等其它方式实现，来替换参数中的Utils.getMetaValue(PushDemoActivity.this,
		// "api_key")
		String key = PushUtil.getMetaValue(MainActivity.this, "api_key");
		Log.i(TAG, "API_KEY" + key);
		String pkgName = this.getPackageName();
		PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, key);
		// Push: 如果想基于地理位置推送，可以打开支持地理位置的推送的开关
		// PushManager.enableLbs(getApplicationContext());

		// Push: 设置自定义的通知样式，具体API介绍见用户手册，如果想使用系统默认的可以不加这段代码
		// 请在通知推送界面中，高级设置->通知栏样式->自定义样式，选中并且填写值：1，
		// 与下方代码中 PushManager.setNotificationBuilder(this, 1, cBuilder)中的第二个参数对应
		// CustomPushNotificationBuilder cBuilder = new
		// CustomPushNotificationBuilder(
		// getApplicationContext(), 0,
		// 0,
		// 0,
		// 0);
		// cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
		// cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND
		// | Notification.DEFAULT_VIBRATE);
		// cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
		// // cBuilder.setLayoutDrawable(resource.getIdentifier(
		// // "simple_notification_icon", "drawable", pkgName));
		// PushManager.setNotificationBuilder(this, 1, cBuilder);

	}

	/**
	 * 初始化UI
	 */
	private void findView() {

		ivSearch = (ImageView) findViewById(R.id.btn_search);
		ivSearch.setOnClickListener(this);
		// 头部
		rl_top_choice = (RelativeLayout) findViewById(R.id.top_rl);
		rl_top_choice.setVisibility(View.GONE);

		tvWhole = (TextView) findViewById(R.id.tv_circle_whole);
		tvGod = (TextView) findViewById(R.id.tv_circle_olympus);
		// 图标
		iv_tab_hall = (ImageView) findViewById(R.id.iv_tab_hall);
		iv_tab_follow = (ImageView) findViewById(R.id.iv_tab_follow);
		// iv_tab_win = (ImageView) findViewById(R.id.iv_tab_win);
		iv_tab_info = (ImageView) findViewById(R.id.iv_tab_info);
		iv_tab_center = (ImageView) findViewById(R.id.iv_tab_center);

		// 图标布局
		layout_tab_hall = (LinearLayout) findViewById(R.id.layout_tab_hall);
		layout_tab_follow = (LinearLayout) findViewById(R.id.layout_tab_follow);
		layout_tab_info = (LinearLayout) findViewById(R.id.layout_tab_info);
		// layout_tab_win = (LinearLayout) findViewById(R.id.layout_tab_win);
		layout_tab_center = (LinearLayout) findViewById(R.id.layout_tab_center);

		// 文字
		tv_tab_hall = (TextView) findViewById(R.id.tv_tab_hall);
		tv_tab_follow = (TextView) findViewById(R.id.tv_tab_follow);
		// tv_tab_win = (TextView) findViewById(R.id.tv_tab_win);
		tv_tab_info = (TextView) findViewById(R.id.tv_tab_info);
		tv_tab_center = (TextView) findViewById(R.id.tv_tab_center);

		// // 这里是启动图片,找了半天
		ll_main = (LinearLayout) this.findViewById(R.id.main);
		// ll_main_1 = (LinearLayout) this.findViewById(R.id.main_1);
		// iv_start=(ImageView) findViewById(R.id.iv_item_head);
		// System.out.println("----" + App.isShow);
		// if (App.isShow) {
		// ll_main.setVisibility(View.VISIBLE);
		//
		// Message message = Message.obtain();
		// message.arg1 = 100;
		// handler.sendMessage(message);
		//
		// }

		rlInfoShow = (RelativeLayout) findViewById(R.id.my_info_show);
		tvInfonum = (TextView) findViewById(R.id.my_info_num);
		setFocuse();
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 100:
				try {
					new Thread().sleep(0);
					if (ll_main.getVisibility() == View.VISIBLE) {
						ll_main.setVisibility(View.GONE);

					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case 200:

				break;
			default:
				break;
			}
		};
	};

	/**
	 * 弹出中奖提示框
	 */
	public void showWinDialog() {
		if (null != vibrator) {
			vibrator.vibrate(500);
		}
		NiftyDialogBuilder dialogBuilder = NiftyDialogBuilder.getInstance(this);
		effect = Effectstype.Shake;
		dialogBuilder.show();
	}

	/**
	 * 查看中奖详情
	 */
	public void toFindWininfo() {

		RequestUtil requestUtil = new RequestUtil(MainActivity.this, false, 0) {
			@Override
			public void responseCallback(JSONObject item) {
				if (RequestUtil.DEBUG)
					Log.i(TAG, "查看中奖详情jsonObject--- " + item.toString());
				try {
					if ("0".equals(item.optString("error"))) {
						String schemeList = item.optString("schemeList");
						JSONArray array = new JSONArray(schemeList);

						JSONArray jsonArray2 = new JSONArray(array.toString());

						Schemes scheme = null;

						if (jsonArray2.length() == 0)
							return;

						// 循环得到每个对象
						for (int i = 0; i < jsonArray2.length(); i++) {
							// 如果取消了 则停止
							JSONObject items = jsonArray2.getJSONObject(i);

							String date = items.getString("date");

							if (!list.contains(date)) {
								falg = false;
								list.add(date);
								listDetail = new ArrayList<Schemes>();

							} else
								falg = true;
							JSONArray detail = new JSONArray(items.getString("dateDetail"));

							for (int j = 0; j < detail.length(); j++) {
								JSONObject items2 = detail.getJSONObject(j);

								scheme = new Schemes();

								scheme.setId(items2.optString("Id"));
								scheme.setSchemeNumber(items2.optString("schemeNumber"));

								scheme.setAssureMoney(items2.optDouble("assureMoney"));
								scheme.setAssureShare(items2.optInt("assureShare"));
								scheme.setBuyed(items2.optString("buyed"));
								scheme.setInitiateName(items2.optString("initiateName"));
								scheme.setInitiateUserID(items2.optString("initiateUserID"));
								scheme.setIsPurchasing(items2.optString("isPurchasing"));
								scheme.setIsuseID(items2.optString("isuseID"));
								scheme.setIsuseName(items2.optString("isuseName"));
								scheme.setLevel(items2.optInt("level"));
								scheme.setLotteryID(items2.optString("lotteryID"));
								scheme.setLotteryName(items2.optString("lotteryName"));
								scheme.setLotteryNumber(items2.optString("lotteryNumber"));
								// 添加buyContent
								JSONArray array_contents = new JSONArray(items2.optString("buyContent"));
								if (array_contents != null) {
									List<LotteryContent> contents = new ArrayList<LotteryContent>();
									LotteryContent lotteryContent = null;
									for (int m = 0; m < array_contents.length(); m++) {
										lotteryContent = new LotteryContent();
										try {
											JSONArray array2 = new JSONArray(array_contents.optString(m));

											lotteryContent.setLotteryNumber(
													array2.getJSONObject(0).optString("lotteryNumber"));
											lotteryContent.setPlayType(array2.getJSONObject(0).optString("playType"));
											lotteryContent.setSumMoney(array2.getJSONObject(0).optString("sumMoney"));
											lotteryContent.setSumNum(array2.getJSONObject(0).optString("sumNum"));
											contents.add(lotteryContent);
										} catch (Exception e) {
											JSONObject array2 = new JSONObject(array_contents.optString(m));

											lotteryContent.setLotteryNumber(array2.optString("lotteryNumber"));
											lotteryContent.setPlayType(array2.optString("playType"));
											lotteryContent.setSumMoney(array2.optString("sumMoney"));
											lotteryContent.setSumNum(array2.optString("sumNum"));
											contents.add(lotteryContent);
										}
									}
									scheme.setBuyContent(contents);
								}

								scheme.setMoney(items2.optInt("money"));
								scheme.setPlayTypeID(items2.optInt("playTypeID"));
								scheme.setPlayTypeName(items2.optString("playTypeName"));
								scheme.setQuashStatus(items2.optInt("quashStatus"));
								scheme.setRecordCount(items2.optInt("RecordCount"));
								scheme.setSchedule(items2.optInt("schedule"));
								scheme.setSchemeBonusScale(items2.optDouble("schemeBonusScale"));
								scheme.setSchemeIsOpened(items2.optString("schemeIsOpened"));
								scheme.setSecrecyLevel(items2.optInt("secrecyLevel"));
								scheme.setSerialNumber(items2.optInt("SerialNumber"));
								scheme.setShare(items2.optInt("share"));
								scheme.setShareMoney(items2.optInt("shareMoney"));
								scheme.setSurplusShare(items2.optInt("surplusShare"));
								scheme.setTitle(items2.optString("title"));
								scheme.setWinMoneyNoWithTax(items2.optInt("winMoneyNoWithTax"));
								scheme.setChaseTaskID(items2.getInt("chaseTaskID"));
								scheme.setWinNumber(items2.optString("winNumber"));

								scheme.setDateTime(items2.optString("datetime"));

								scheme.setDescription(items2.optString("description"));

								scheme.setIsChase(items2.optInt("isChase"));

								scheme.setMultiple(items2.optInt("multiple"));
								scheme.setFromClient(items2.getInt("FromClient"));
								scheme.setMyBuyMoney(items2.getInt("myBuyMoney") + "");

								scheme.setMyBuyShare(items2.optInt("myBuyShare"));

								listDetail.add(scheme);
							}
							if (!falg)
								listAllSchemes.add(listDetail);
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
					if (RequestUtil.DEBUG)
						Log.e(TAG, "查看中奖详情错误" + e.getMessage());
				}
				if (listAllSchemes == null || listAllSchemes.size() == 0 || listAllSchemes.get(0).size() == 0) {
					return;
				}
				Schemes scheme = listAllSchemes.get(0).get(0);
				Intent intent = null;

				if (scheme.getIsChase() == 0)
					if ("72".equals(scheme.getLotteryID()) || "73".equals(scheme.getLotteryID()))
						intent = new Intent(context, MyCommonLotteryInfo_jc.class);
					else
						intent = new Intent(context, MyCommonLotteryInfo.class);
				else
					intent = new Intent(context, MyFollowLotteryInfo.class);
				App.scheme = scheme;
				intent.putExtra("scheme", scheme);
				startActivity(intent);
			}

			@Override
			public void responseError(VolleyError error) {
				if (RequestUtil.DEBUG)
					Log.e(TAG, "查看中奖详情出错--- " + error.getMessage());
			}
		};
		requestUtil.getWinDetail();
		requestUtils.add(requestUtil);
	}

	/* 得到当前版本号 */
	public void getVersion() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			App.version = info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void setFragment() {
		// if(indexId ==R.id.layout_tab_follow) {
		// rl_top_choice.setVisibility(View.VISIBLE);
		// setFocuse();
		// iv_tab_follow.setBackgroundResource(R.drawable.main_tab3_selected);
		// tv_tab_follow.setTextColor(getResources().getColor(R.color.main_red));
		//
		//
		//
		// if (ChoiceIndex == 1) {
		// transaction.replace(R.id.main_center, new CircleFragment_viewpage_whole(),
		// "follow");
		// } else {
		// transaction.replace(R.id.main_center, new CircleFragment_viewpage_god(),
		// "follow");
		// }
		//
		// transaction.commitAllowingStateLoss();
		// }else if (indexId ==R.id.layout_tab_hall) {
		indexId = R.id.layout_tab_hall;
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.main_center, new HallFragment(), "hall");

		transaction.commitAllowingStateLoss();

		setFocuse();
		iv_tab_hall.setBackgroundResource(R.drawable.main_tab1_selected);
		tv_tab_hall.setTextColor(getResources().getColor(R.color.main_red));
		// }

	}

	/**
	 * 绑定监听
	 */
	private void setListener() {
		dialog = new ConfirmDialog(this, R.style.dialog);
		layout_tab_hall.setOnClickListener(this);
		layout_tab_follow.setOnClickListener(this);
		// layout_tab_win.setOnClickListener(this);
		layout_tab_info.setOnClickListener(this);
		layout_tab_center.setOnClickListener(this);
		tvWhole.setOnClickListener(this);
		tvGod.setOnClickListener(this);
	}

	/*
	 * 版本检测版本的更新
	 */
	private void updateversions() {
		RequestUtil requestUtil = new RequestUtil(MainActivity.this, false, 0) {
			@Override
			public void responseCallback(JSONObject jsonObject) {
				if (RequestUtil.DEBUG)
					Log.i(TAG, "更新jsonObject--- " + jsonObject.toString());
				App.appobject.setUpgrade(jsonObject.optString("upgrade"));
				// App.appobject.setApkName(jsonObject.optString("apkName"));
				App.appobject.setVersionCode(jsonObject.optString("currentappversion"));
				App.appobject.setDownLoadUrl(jsonObject.optString("downLoadUrl"));

				// App.appobject.setSort(3);// 排序方式
				if (App.appobject.getUpgrade().equals("True")) {
					// 这里来检测版本是否需要更新
					mUpdateManager = new UpdateManager(MainActivity.this, App.appobject.getDownLoadUrl());
					if (RequestUtil.DEBUG)
						Log.i(TAG, "更新url--- " + App.appobject.getDownLoadUrl());
					mUpdateManager.checkUpdateInfo();
				}
			}

			@Override
			public void responseError(VolleyError error) {
				if (RequestUtil.DEBUG)
					Log.e(TAG, "检查更新出错--- " + error.getMessage());
			}
		};
		requestUtil.checkUpdateApp();
		requestUtils.add(requestUtil);

	}

	/**
	 * 获取合买佣金比列和合买最少购买比列
	 */
	public void getScaleParams() {
		RequestUtil requestUtil = new RequestUtil(MainActivity.this, false, 0) {
			@Override
			public void responseCallback(JSONObject jsonObject) {
				if (RequestUtil.DEBUG)
					// Log.i(TAG,"获取合买佣金比列和合买最少购买比列jsonObject--- "+ jsonObject.toString());
					if (null != jsonObject) {
						if ("0".equals(jsonObject.optString("error"))) {
							App.followCommissionScale = jsonObject.optString("yongjin"); // 合买佣金比列
							App.followLeastBuyScale = jsonObject.optString("rengou"); // 合买最少购买比列
						}
					} else {
						if (RequestUtil.DEBUG)
							Log.e(TAG, "获取合买佣金比列和合买最少购买比列失败---返回结果为空");
					}
			}

			@Override
			public void responseError(VolleyError error) {
				if (RequestUtil.DEBUG)
					Log.e(TAG, "获取合买佣金比列和合买最少购买比列出错--- " + error.getMessage());
			}
		};
		requestUtil.getBuyParams();
		requestUtils.add(requestUtil);
	}

	/**
	 * 获取最近一条中奖信息
	 */
	public void getCurrentWinInfo(String uid) {
		RequestUtil requestUtil = new RequestUtil(MainActivity.this, false, 0) {
			@Override
			public void responseCallback(JSONObject jsonObject) {
				if (RequestUtil.DEBUG)
					Log.i(TAG, "获取最近一条中奖信息jsonObject--- " + jsonObject.toString());
				if (null != jsonObject) {
					if ("0".equals(jsonObject.optString("error"))) {// 无中奖
						isWin = false;
					} else if ("1".equals(jsonObject.optString("error"))) {// 有中奖信息
						isWin = true;
					}
				} else {
					if (RequestUtil.DEBUG)
						Log.e(TAG, "获取最近一条中奖信息---返回结果为空");
					isWin = false;
				}
			}

			@Override
			public void responseError(VolleyError error) {
				if (RequestUtil.DEBUG)
					Log.e(TAG, "获取最近一条中奖信息出错--- " + error.getMessage());
				isWin = false;
			}
		};
		requestUtil.getCurrentWinInfo(uid);
		requestUtils.add(requestUtil);
	}

	@Override
	public void onClick(View v) {
		transaction = getSupportFragmentManager().beginTransaction();

		switch (v.getId()) {
		// 购彩大厅
		case R.id.layout_tab_hall:
			if (R.id.layout_tab_hall != indexId) {
				rl_top_choice.setVisibility(View.GONE);
				getShowNum();
				indexId = R.id.layout_tab_hall;
				setFocuse();
				iv_tab_hall.setBackgroundResource(R.drawable.main_tab1_selected);
				tv_tab_hall.setTextColor(getResources().getColor(R.color.main_red));
				transaction.replace(R.id.main_center, new HallFragment(), "hall");
				transaction.commitAllowingStateLoss();
				// switchFragment(mHallFragment);
			}
			break;
		// 比分直播 cp资讯
		case R.id.layout_tab_info:
			if (R.id.layout_tab_info != indexId) {
				getShowNum();
				rl_top_choice.setVisibility(View.GONE);
				indexId = R.id.layout_tab_info;
				setFocuse();
				iv_tab_info.setBackgroundResource(R.drawable.main_tab2_selected);
				tv_tab_info.setTextColor(getResources().getColor(R.color.main_red));
				transaction.replace(R.id.main_center, new myLiveScoresFragment(), "livescores");

				transaction.commitAllowingStateLoss();
				// switchFragment(mLiveScoresFragment);
			}
			break;
		// 合买大厅
		case R.id.layout_tab_follow:
			if (R.id.layout_tab_follow != indexId) {

				if (null == App.user) {
					intent = new Intent(MainActivity.this, LoginActivity.class);
					MainActivity.this.startActivity(intent);
				} else {
					getShowNum();
					rl_top_choice.setVisibility(View.VISIBLE);
					indexId = R.id.layout_tab_follow;
					setFocuse();
					iv_tab_follow.setBackgroundResource(R.drawable.main_tab3_selected);
					tv_tab_follow.setTextColor(getResources().getColor(R.color.main_red));
					if (ChoiceIndex == 1) {
						tvWhole.setBackgroundResource(R.drawable.top_choice_bg);
						tvGod.setBackgroundResource(R.drawable.top_choice_lr_bg);

						tvWhole.setTextColor(getResources().getColor(R.color.red));
						tvGod.setTextColor(getResources().getColor(R.color.white));
						transaction.replace(R.id.main_center, new CircleFragment_viewpage_whole(), "follow");
					} else {
						tvWhole.setBackgroundResource(R.drawable.top_choice_lr_bg);
						tvGod.setBackgroundResource(R.drawable.top_choice_bg);
						tvWhole.setTextColor(getResources().getColor(R.color.white));
						tvGod.setTextColor(getResources().getColor(R.color.red));
						transaction.replace(R.id.main_center, new CircleFragment_viewpage_god(), "follow");

					}

					transaction.commitAllowingStateLoss();
					// switchFragment(mFollowFragment);
				}
			}
			break;
		// 开奖公告
		/*
		 * case R.id.layout_tab_win: if (R.id.layout_tab_win != indexId) { indexId =
		 * R.id.layout_tab_win; setFocuse();
		 * iv_tab_win.setBackgroundResource(R.drawable.bottom_openwin_check);
		 * tv_tab_win.setTextColor(getResources().getColor( R.color.main_red));
		 * transaction.replace(R.id.main_center, new WinLotteryFragment(),
		 * "winLottery"); transaction.commitAllowingStateLoss(); //
		 * switchFragment(mWinLotteryFragment); } break;
		 */

		// 个人中心
		case R.id.layout_tab_center:
			if (R.id.layout_tab_center != indexId) {
				getShowNum();
				rl_top_choice.setVisibility(View.GONE);
				indexId = R.id.layout_tab_center;
				setFocuse();
				iv_tab_center.setBackgroundResource(R.drawable.main_tab5_selected);
				tv_tab_center.setTextColor(getResources().getColor(R.color.main_red));
				ToMyCenterActivity();
			}
			break;
		case R.id.tv_circle_whole:
			if (ChoiceIndex != 1) {
				ChoiceIndex = 1;
				getShowNum();
				tvWhole.setBackgroundResource(R.drawable.top_choice_bg);
				tvGod.setBackgroundResource(R.drawable.top_choice_lr_bg);
				tvWhole.setTextColor(getResources().getColor(R.color.red));
				tvGod.setTextColor(getResources().getColor(R.color.white));
				transaction.replace(R.id.main_center, new CircleFragment_viewpage_whole(), "follow");

				transaction.commitAllowingStateLoss();
			}
			break;
		case R.id.tv_circle_olympus:
			if (ChoiceIndex != 2) {
				ChoiceIndex = 2;
				getShowNum();
				tvWhole.setBackgroundResource(R.drawable.top_choice_lr_bg);
				tvGod.setBackgroundResource(R.drawable.top_choice_bg);
				tvWhole.setTextColor(getResources().getColor(R.color.white));
				tvGod.setTextColor(getResources().getColor(R.color.red));
				transaction.replace(R.id.main_center, new CircleFragment_viewpage_god(), "follow");

				transaction.commitAllowingStateLoss();
			}
			break;
		case R.id.btn_search:
			Intent intentSearch = new Intent(MainActivity.this, SearchForPersonActivity.class);
			startActivity(intentSearch);
			// Toast.makeText(context, "搜索", Toast.LENGTH_SHORT).show();
			break;
		}
	}

	// public Fragment mFragment;
	public FragmentManager mFragmentManager;

	private void switchFragment(Fragment fragment) {
		if (fragment != mFragment) {
			if (!fragment.isAdded()) {
				getSupportFragmentManager().beginTransaction().add(R.id.main_center, fragment).show(fragment)
						.commitAllowingStateLoss();
			} else {
				getSupportFragmentManager().beginTransaction().hide(mFragment).show(fragment).commitAllowingStateLoss();
			}
			mFragment = fragment;
		}
	}

	/**
	 * 重写返回键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if (System.currentTimeMillis() - firstTime > 2000) {
				Toast.makeText(MainActivity.this, "再按一次退出" + getText(R.string.app_name) + "程序", Toast.LENGTH_SHORT)
						.show();
				firstTime = System.currentTimeMillis();
			} else {
				SharedPreferences myAhare = getSharedPreferences("infonum", Activity.MODE_PRIVATE);
				// 实例化SharedPreferences.Editor对象（第二步）
				SharedPreferences.Editor editor = myAhare.edit();
				// 用putString的方法保存数据
				editor.putString("num", App.getInfoNum);

				editor.commit();
				Log.e("sss", App.getInfoNum);
				ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
				manager.restartPackage(getPackageName());
				for (Activity activity : App.activityS) {
					activity.finish();
				}
				MainActivity.this.finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 点击个人中心
	 */
	private void ToMyCenterActivity() {
		if (null == App.user) {
			intent = new Intent(MainActivity.this, LoginActivity.class);
			MainActivity.this.startActivity(intent);
		} else {
			transaction.replace(R.id.main_center, new MyCenterFragment(), "center");
			transaction.commitAllowingStateLoss();

		}
	}

	Fragment liveScoresFragment;

	public void toLive(int pos) {

		indexId = R.id.layout_tab_info;
		// Log.i("Hall", "Main"+pos);
		liveScoresFragment = myLiveScoresFragment.newInstance(pos);

		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		setFocuse();
		iv_tab_info.setBackgroundResource(R.drawable.main_tab2_selected);
		tv_tab_info.setTextColor(getResources().getColor(R.color.main_red));
		fragmentTransaction.replace(R.id.main_center, liveScoresFragment, "livescores");
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commitAllowingStateLoss();

	}

	public static void toCenter() {
		// switchFragment(mMyCenterFragment);
		try {
			// transaction.add(R.id.main_center, new MyCenterFragment()).hide()
			transaction.replace(R.id.main_center, new MyCenterFragment(), "center");
			transaction.commitAllowingStateLoss();

		} catch (Exception e) {
			Log.i("x", "登陆错误" + e.getMessage());
		}
	}

	public static void toHall() {
		// switchFragment(mMyCenterFragment);
		try {

			// transaction.add(R.id.main_center, new MyCenterFragment()).hide()
			transaction.replace(R.id.main_center, new HallFragment(), "hall");
			transaction.commitAllowingStateLoss();

		} catch (Exception e) {
			Log.i("x", "登陆错误" + e.getMessage());
		}
	}

	@Override
	protected void onStop() {
		Log.i(TAG, "onStop");
		super.onStop();
		cancelAll();
	}

	/**
	 * 取消所有请求
	 */
	private void cancelAll() {
		if (null != requestUtils && 0 != requestUtils.size()) {
			for (int i = 0; i < requestUtils.size(); i++) {
				RequestUtil requestUtil = requestUtils.get(i);
				if (null != requestUtil) {
					Request request = requestUtil.getRequest();
					if (null != request)
						request.cancel();
				}
			}
		}
	}

	/**
	 * 设置未选中的状态
	 */
	private void setFocuse() {
		iv_tab_hall.setBackgroundResource(R.drawable.main_tab1_normal);
		tv_tab_hall.setTextColor(getResources().getColor(R.color.main_gray));
		iv_tab_follow.setBackgroundResource(R.drawable.main_tab3_normal);
		tv_tab_follow.setTextColor(getResources().getColor(R.color.main_gray));
		// iv_tab_win.setBackgroundResource(R.drawable.bottom_openwin);
		// tv_tab_win.setTextColor(getResources().getColor(R.color.main_gray));
		iv_tab_info.setBackgroundResource(R.drawable.main_tab2_normal);
		tv_tab_info.setTextColor(getResources().getColor(R.color.main_gray));
		iv_tab_center.setBackgroundResource(R.drawable.main_tab5_normal);
		tv_tab_center.setTextColor(getResources().getColor(R.color.main_gray));
	}

	@Override
	protected void onDestroy() {
		Log.i(TAG, "onDestroy");
		
	
		App.activityS.remove(this);
		super.onDestroy();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		setFragment();
		super.onNewIntent(intent);
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
		
		for (int i = 0; i < App.activityS1.size(); i++) {
			App.activityS1.get(i).finish();
			
			Log.e("xxxxx", "main1清除所有"+App.activityS1.get(i));
		}
		App.activityS1.clear();
		Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_center);
		if (fragment instanceof CircleFragment)
			indexId = R.id.layout_tab_follow;

		if (fragment instanceof LiveScoresFragment)
			indexId = R.id.layout_tab_info;
		if (fragment instanceof MyCenterFragment) {
			indexId = R.id.layout_tab_center;
			setFocuse();
			iv_tab_center.setBackgroundResource(R.drawable.main_tab5_selected);
			tv_tab_center.setTextColor(getResources().getColor(R.color.main_red));
		}

		/*
		 * if (fragment instanceof WinLotteryFragment) indexId = R.id.layout_tab_win;
		 */
		if (fragment instanceof HallFragment) {
			indexId = R.id.layout_tab_hall;
			setFocuse();
			iv_tab_hall.setBackgroundResource(R.drawable.main_tab1_selected);
			tv_tab_hall.setTextColor(getResources().getColor(R.color.main_red));
		}

		SharedPreferences settings = context.getSharedPreferences("app_user", 0);
		String uid = settings.getString("uid", "");
		if (!"".equals(uid) && !"-1".equals(uid)) {
			getCurrentWinInfo(uid);
		}
		// showWinDialog();
		if (App.choiceNum) {
			App.choiceNum=false;
			onClick(layout_tab_follow);
			
		}
		
		
		if (App.getInfoNum.equals("0")||Integer.parseInt(App.getInfoNum)<0) {
			
		rlInfoShow.setVisibility(View.GONE);
		tvInfonum.setText(App.getInfoNum);
		App.getInfoNum="0";
			
		}else {
			rlInfoShow.setVisibility(View.VISIBLE);
			if (Integer.parseInt(App.getInfoNum)>99) {
				tvInfonum.setText("99+");
			}else {
				tvInfonum.setText(App.getInfoNum);
			}
		}
	}

	
	
	public void update() {
		Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_center);
		if (fragment instanceof HallFragment)
			((HallFragment) fragment).update();
	}

	@Override
	protected void onRestart() {
		Log.i(TAG, "onRestart");
		super.onRestart();

	}

	@Override
	public void onCancleClick() {
		// TODO Auto-generated method stub

		Toast.makeText(getApplication(), "sasad", Toast.LENGTH_SHORT).show();
		;

	}

	@Override
	public void onSureClick() {
		// TODO Auto-generated method stub

	}
public void  getShowNum() {
	if (App.getInfoNum.equals("0")) {
		
		rlInfoShow.setVisibility(View.GONE);
		tvInfonum.setText(App.getInfoNum);
			
		}else {
			rlInfoShow.setVisibility(View.VISIBLE);
			if (Integer.parseInt(App.getInfoNum)>99) {
				tvInfonum.setText("99+");
			}else {
				tvInfonum.setText(App.getInfoNum);
			}
		}
}
}
